package com.ts.api.http.org.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.id.IdUtils;
import com.gitee.apanlh.util.reflection.ClassConvertUtils;
import com.ts.api.http.org.entity.apply.OrgApplyZhongYuanXingMeng;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.org.handler.ApiOrgPhoneMd5ConvertHandler;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5Apply;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5DataExchange;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 *  中元鑫梦
 *
 *  @author WJB
 */
@ApiPlan(productId = "35", type = ApiPlanConvertType.ORG_PHONE_MD5)
public class ApiOrgPhoneMd5ZhongYuanXingMeng implements ApiOrgPhoneMd5ConvertHandler {

    private static final String APPID = "zyiy8ettim7lcrcff4";
    private static final String KEY = "0gxihsi86mvr4d4j0s6chot0eppi6ewf";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        Map<Object, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("phoneMd5", apiDataExchangeParameter.getPhoneMd5());
        });
        String sendJson = JsonUtils.toJson(map);
        return sendJson;
    }

    @Override
    public RespOrgPhoneMd5DataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }

        JSONObject data = jsonObject.getJSONObject("data");
        boolean code = Eq.object(jsonObject.getInteger("code"), 200);
        boolean status = Eq.object(data.getInteger("status"), 0);
        if (!code && !status) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        return RespOrgPhoneMd5DataExchange.ofSuc();
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        OrgApplyZhongYuanXingMeng data = new OrgApplyZhongYuanXingMeng();
        //  城市
        data.setCity(apiApplyParameter.getCity());
        //  姓名
        data.setName(apiApplyParameter.getUserName());
        //  手机号
        data.setPhone(apiApplyParameter.getPhone());
        data.setTimestamp(ClassConvertUtils.toStr(System.currentTimeMillis() / 1000));
        //  appid
        data.setAppid(APPID);
        data.setNoncestr(IdUtils.generateIdNumberStr());
        //  贷款金额
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 30000)
                .when(apiApplyParameter.getLoanAmount(), "2", 50000)
                .when(apiApplyParameter.getLoanAmount(), "3", 100000)
                .when(apiApplyParameter.getLoanAmount(), "4", 200000)
                .end();
        data.setMoney(money);
        //  拓展判断信息
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        data.setZizhi(apiFieldConverter.getExtendInfo());
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("appid", data.getAppid());
            newMap.put("appkey", KEY);
            newMap.put("noncestr", data.getNoncestr());
            newMap.put("timestamp", data.getTimestamp());
            newMap.put("city", data.getCity());
            newMap.put("phone", data.getPhone());
            newMap.put("money", data.getMoney());
            newMap.put("name", data.getName());
            newMap.put("zizhi", data.getZizhi());
        });

        String sign = generateSign(map, KEY);
        data.setSign(sign);
        return JsonUtils.toJson(data);
    }

    // 生成签名的方法
    public static String generateSign(Map<String, Object> params, String appkey) {
        // 按照字段名的ASCII码排序
        List<String> sortedKeys = new ArrayList<>(params.keySet());
        Collections.sort(sortedKeys);

        // 拼接字符串
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : sortedKeys) {
            // 拼接参数（key=value）
            stringBuilder.append(key).append("=").append(params.get(key)).append("&");
        }

        // 去掉最后的 '&' 符号
        stringBuilder.setLength(stringBuilder.length() - 1);

        // 进行 SHA-1 加密并返回签名
        return sha1(stringBuilder.toString());
    }

    // SHA-1 加密
    public static String sha1(String input) {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            byte[] bytes = sha1.digest(input.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                result.append(String.format("%02x", b));
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-1 Algorithm not found", e);
        }
    }

    @Override
    public RespOrgPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("status"), 200)) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        return RespOrgPhoneMd5Apply.ofSuc();
    }
}
